// 活动管理页面
const { createActivity, getActivityList, updateActivity, deleteActivity, updateActivityStatus } = require('../../../api/activities')
const { processActivityData, stripHtmlTags, formatDateTime } = require('../../../utils/dataFormatter')
const { getCurrentUser } = require('../../../utils/auth')

Page({
  data: {
    loading: false,
    activities: [],
    allActivities: [], // 保存所有原始数据
    currentDate: '', // 当前日期，用于限制picker的最小日期
    stats: {
      totalCount: 0,
      activeCount: 0,
      completedCount: 0,
      upcomingCount: 0
    },
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '管理数据加载中...',
    // 弹窗控制
    showCreateModal: false,
    showEditModal: false,
    // 表单数据
    formData: {
      title: '',
      subtitle: '',
      description: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
      registrationRequired: true, // 是否需要报名，默认为true
      registrationDeadlineDate: '',
      registrationDeadlineTime: '',
      maxParticipants: '',
      contact: '',
      phone: '',
      location: '',
      publisher: '',
      images: []
    },
    // 编辑表单数据
    editFormData: {
      id: null,
      title: '',
      subtitle: '',
      description: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
      registrationRequired: true,
      registrationDeadlineDate: '',
      registrationDeadlineTime: '',
      maxParticipants: '',
      contact: '',
      phone: '',
      location: '',
      publisher: '',
      images: []
    },
    // 表单错误状态
    errors: {
      title: '',
      subtitle: '',
      description: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
      registrationDeadlineDate: '',
      registrationDeadlineTime: '',
      maxParticipants: '',
      contact: '',
      phone: '',
      location: '',
      publisher: '',
      images: ''
    },
    // 编辑表单错误状态
    editErrors: {
      title: '',
      subtitle: '',
      description: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
      registrationDeadlineDate: '',
      registrationDeadlineTime: '',
      maxParticipants: '',
      contact: '',
      phone: '',
      location: '',
      publisher: '',
      images: ''
    }
  },

  // 显示全局加载
  showGlobalLoading(text = '管理数据加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad() {
    console.log('活动管理页面加载成功')
    // 初始化当前日期
    const now = new Date()
    const currentDate = now.toISOString().split('T')[0]
    this.setData({ currentDate })
    this.loadActivities()
  },

  // 验证内容是否有效
  validateContent(content) {
    if (!content || typeof content !== 'string') {
      return false
    }
    
    // 检查是否包含明显的乱码模式
    const invalidPatterns = [
      /[v]{3,}/g, // 连续多个v字符
      /[a-zA-Z]{10,}/g, // 连续10个以上英文字符
      /[^\u4e00-\u9fa5a-zA-Z0-9\s<>\/="'.,!?;:()\-]/g, // 包含特殊字符
      /(.)\1{5,}/g // 连续6个以上相同字符
    ]
    
    for (let pattern of invalidPatterns) {
      if (pattern.test(content)) {
        return false
      }
    }
    
    // 检查内容长度是否合理
    if (content.length < 5 || content.length > 2000) {
      return false
    }
    
    // 检查是否包含有意义的中文内容
    const chineseChars = content.match(/[\u4e00-\u9fa5]/g)
    if (!chineseChars || chineseChars.length < 3) {
      return false
    }
    
    return true
  },

  // 生成随机背景色
  generateRandomBackgroundColor() {
    // 生成适合活动的随机颜色，避免白色、接近白色和沉闷的灰紫色
    let color
    let attempts = 0
    const maxAttempts = 50 // 最大尝试次数，避免无限循环
    
    do {
      // 生成随机RGB值（范围：30-180，避免过深或过浅）
      const r = Math.floor(Math.random() * 151) + 30  // 30-180
      const g = Math.floor(Math.random() * 151) + 30  // 30-180
      const b = Math.floor(Math.random() * 151) + 30  // 30-180
      
      // 转换为十六进制
      const hexR = r.toString(16).padStart(2, '0')
      const hexG = g.toString(16).padStart(2, '0')
      const hexB = b.toString(16).padStart(2, '0')
      
      color = `#${hexR}${hexG}${hexB}`
      
      // 检查是否为白色或接近白色（RGB值都大于160）
      const isTooLight = r > 160 && g > 160 && b > 160
      
      // 检查是否为沉闷的灰紫色（RGB值相近且偏低饱和度）
      const maxDiff = Math.max(r, g, b) - Math.min(r, g, b)
      const avgValue = (r + g + b) / 3
      const isDullGrayPurple = maxDiff < 30 && avgValue < 120 && avgValue > 60
      
      // 检查是否为过于暗淡的颜色（平均亮度太低）
      const isTooDark = avgValue < 50
      
      attempts++
      
      // 如果颜色合适（不太亮、不是沉闷灰紫色、不太暗），就使用这个颜色
      if (!isTooLight && !isDullGrayPurple && !isTooDark) {
        break
      }
      
    } while (attempts < maxAttempts)
    
    // 如果尝试次数过多，使用一个适合活动的安全颜色
    if (attempts >= maxAttempts) {
      const safeColors = [
        '#4CAF50', '#2196F3', '#FF9800', '#E91E63', '#9C27B0',
        '#00BCD4', '#8BC34A', '#FF5722', '#3F51B5', '#FFC107',
        '#795548', '#607D8B', '#4CAF50', '#FF6B6B', '#4ECDC4',
        '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8'
      ]
      color = safeColors[Math.floor(Math.random() * safeColors.length)]
    }
    
    console.log('生成随机背景色:', color)
    return color
  },


  onShow() {
    console.log('活动管理页面显示')
  },

  // 加载活动数据
  async loadActivities() {
    console.log('加载活动数据')
    this.setData({ loading: true })
    
    try {
      // 调用API获取活动列表
      const result = await getActivityList({
        page: 1,
        limit: 100 // 获取所有活动
      })
      
      if (result.success) {
        console.log('服务器返回的原始活动数据（前3条）:', result.data.activities.slice(0, 3))
        
        const activities = result.data.activities.map(activity => {
          console.log('处理活动数据:', {
            id: activity.id,
            title: activity.title,
            start_date: activity.start_date,
            start_time: activity.start_time,
            end_date: activity.end_date,
            end_time: activity.end_time
          })
          
          // 使用工具函数处理活动数据
          const processedActivity = processActivityData(activity, {
            stripHtml: true,
            truncateDescription: true,
            descriptionLength: 60,
            formatTime: true
          })
          
          return {
            id: activity.id,
            title: activity.title,
            subtitle: activity.subtitle,
            description: processedActivity.description,
            startTime: this.formatActivityTime(activity.start_date, activity.start_time),
            endTime: this.formatActivityTime(activity.end_date, activity.end_time),
            // 确保日期时间格式符合picker组件要求
            startDate: this.formatDateForPicker(activity.start_date),
            startTimeForPicker: this.formatTimeForPicker(activity.start_time),
            endDate: this.formatDateForPicker(activity.end_date),
            endTimeForPicker: this.formatTimeForPicker(activity.end_time),
            status: activity.status,
            statusText: this.getStatusText(activity.status),
            participants: activity.current_participants || 0,
            maxParticipants: activity.max_participants,
            contact: activity.contact_person,
            phone: activity.contact_phone,
            location: activity.location || '',
            publisher: activity.organizer || '',
            images: activity.images ? activity.images.map(img => img.image_url) : [],
            createTime: formatDateTime(activity.created_at),
            updateTime: formatDateTime(activity.updated_at),
            // 报名相关字段
            registrationRequired: activity.registration_required !== undefined ? activity.registration_required : true,
            registrationDeadline: activity.registration_deadline,
            registrationDeadlineDate: activity.registration_deadline ? this.formatDateForPicker(activity.registration_deadline) : '',
            registrationDeadlineTime: activity.registration_deadline ? this.formatTimeForPicker(activity.registration_deadline) : '',
            // 保存原始内容用于编辑
            originalContent: activity.content,
            // 保存原始时间数据用于编辑（这些数据直接来自数据库，无需额外处理）
            originalStartDate: activity.start_date,
            originalStartTime: activity.start_time,
            originalEndDate: activity.end_date,
            originalEndTime: activity.end_time,
            originalRegistrationDeadline: activity.registration_deadline
          }
        })

        const stats = {
          totalCount: activities.length,
          activeCount: activities.filter(item => item.status === 'active').length,
          completedCount: activities.filter(item => item.status === 'completed').length,
          upcomingCount: activities.filter(item => item.status === 'upcoming').length
        }

        this.setData({
          activities: activities,
          allActivities: activities,
          stats: stats,
          loading: false
        })
      } else {
        throw new Error(result.message || '获取活动列表失败')
      }
    } catch (error) {
      console.error('加载活动数据失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载数据失败，请重试',
        icon: 'none'
      })
    }
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'upcoming': '即将开始',
      'active': '进行中',
      'completed': '已结束',
      'cancelled': '已取消'
    }
    return statusMap[status] || '未知状态'
  },

  // 格式化活动时间显示
  formatActivityTime(date, time) {
    if (!date || !time) return ''
    
    // 将日期和时间组合成完整的日期时间字符串
    const dateTime = `${date} ${time}`
    
    // 如果已经是完整格式，直接返回
    if (dateTime.includes(' ') && !dateTime.includes('T')) {
      return dateTime
    }
    
    return dateTime
  },

  // 从日期时间字符串中解析日期部分
  parseDateFromDateTime(dateTimeString) {
    if (!dateTimeString) return ''
    
    console.log('解析日期:', dateTimeString)
    
    // 如果已经是纯日期格式 (YYYY-MM-DD)，直接返回
    if (dateTimeString.match(/^\d{4}-\d{2}-\d{2}$/)) {
      console.log('纯日期格式:', dateTimeString)
      return dateTimeString
    }
    
    // 处理ISO格式 (2024-01-01T10:00:00.000Z 或 2024-01-01T10:00:00)
    if (dateTimeString.includes('T')) {
      // 避免时区转换问题，直接提取日期部分
      const datePart = dateTimeString.split('T')[0]
      console.log('ISO格式解析结果:', datePart)
      return datePart
    }
    
    // 处理空格分隔格式 (2024-01-01 10:00:00)
    if (dateTimeString.includes(' ')) {
      const datePart = dateTimeString.split(' ')[0]
      console.log('空格格式解析结果:', datePart)
      return datePart
    }
    
    // 如果只是时间格式，返回空字符串
    if (dateTimeString.match(/^\d{2}:\d{2}:\d{2}$/)) {
      console.log('纯时间格式，返回空字符串')
      return ''
    }
    
    console.log('无法解析的格式，返回空字符串')
    return ''
  },

  // 从日期时间字符串中解析时间部分
  parseTimeFromDateTime(dateTimeString) {
    if (!dateTimeString) return ''
    
    console.log('解析时间:', dateTimeString)
    
    // 如果已经是HH:mm格式，直接返回
    if (dateTimeString.match(/^\d{2}:\d{2}$/)) {
      console.log('HH:mm格式:', dateTimeString)
      return dateTimeString
    }
    
    // 如果只是时间格式 (HH:mm:ss)，提取HH:mm部分
    if (dateTimeString.match(/^\d{2}:\d{2}:\d{2}$/)) {
      const result = dateTimeString.split(':').slice(0, 2).join(':')
      console.log('纯时间格式解析结果:', result)
      return result
    }
    
    // 处理ISO格式 (2024-01-01T10:00:00.000Z 或 2024-01-01T10:00:00)
    if (dateTimeString.includes('T')) {
      const timePart = dateTimeString.split('T')[1]
      if (timePart) {
        // 提取HH:mm部分，去掉秒和毫秒
        const result = timePart.split(':').slice(0, 2).join(':')
        console.log('ISO格式时间解析结果:', result)
        return result
      }
    }
    
    // 处理空格分隔格式 (2024-01-01 10:00:00)
    if (dateTimeString.includes(' ')) {
      const timePart = dateTimeString.split(' ')[1]
      if (timePart) {
        // 提取HH:mm部分，去掉秒
        const result = timePart.split(':').slice(0, 2).join(':')
        console.log('空格格式时间解析结果:', result)
        return result
      }
    }
    
    console.log('无法解析的时间格式，返回空字符串')
    return ''
  },

  // 显示创建活动弹窗
  onShowCreateModal() {
    console.log('显示创建活动弹窗')
    this.setData({
      showCreateModal: true,
      formData: {
        title: '',
        subtitle: '',
        description: '',
        startDate: '',
        startTime: '',
        endDate: '',
        endTime: '',
        registrationRequired: true, // 是否需要报名，默认为true
        registrationDeadlineDate: '',
        registrationDeadlineTime: '',
        maxParticipants: '',
        contact: '',
        phone: '',
        location: '',
        publisher: '',
        images: []
      },
      errors: {
        title: '', subtitle: '', description: '', startDate: '', startTime: '', endDate: '', endTime: '', registrationDeadlineDate: '', registrationDeadlineTime: '', maxParticipants: '', contact: '', phone: '', location: '', publisher: '', images: ''
      }
    })
  },

  // 隐藏创建活动弹窗
  onHideCreateModal() {
    this.setData({ showCreateModal: false })
  },

  // 编辑活动按钮点击
  onShowEditModal(e) {
    const { activity } = e.currentTarget.dataset
    console.log('显示编辑活动弹窗 - 原始活动数据:', activity)
    console.log('原始时间字段:', {
      originalStartDate: activity.originalStartDate,
      originalStartTime: activity.originalStartTime,
      originalEndDate: activity.originalEndDate,
      originalEndTime: activity.originalEndTime,
      originalRegistrationDeadline: activity.originalRegistrationDeadline
    })
    
    // 使用格式化函数确保picker组件能正确显示和保存数据
    const startDate = this.formatDateForPicker(activity.originalStartDate || activity.startDate)
    const startTime = this.formatTimeForPicker(activity.originalStartTime || activity.startTime)
    const endDate = this.formatDateForPicker(activity.originalEndDate || activity.endDate)
    const endTime = this.formatTimeForPicker(activity.originalEndTime || activity.endTime)
    const registrationDeadlineDate = activity.originalRegistrationDeadline ? 
      this.formatDateForPicker(activity.originalRegistrationDeadline) : 
      this.formatDateForPicker(activity.registrationDeadlineDate)
    const registrationDeadlineTime = activity.originalRegistrationDeadline ? 
      this.formatTimeForPicker(activity.originalRegistrationDeadline) : 
      this.formatTimeForPicker(activity.registrationDeadlineTime)
    
    console.log('编辑弹窗时间解析结果:', {
      startDate, startTime, endDate, endTime, registrationDeadlineDate, registrationDeadlineTime
    })
    
    // 回显活动数据到编辑表单
    this.setData({
      showEditModal: true,
      editFormData: {
        id: activity.id,
        title: activity.title,
        subtitle: activity.subtitle,
        description: activity.originalContent || activity.description, // 使用原始内容
        startDate: startDate,
        startTime: startTime,
        endDate: endDate,
        endTime: endTime,
        registrationRequired: activity.registrationRequired,
        registrationDeadlineDate: registrationDeadlineDate,
        registrationDeadlineTime: registrationDeadlineTime,
        maxParticipants: activity.maxParticipants,
        contact: activity.contact,
        phone: activity.phone,
        location: activity.location,
        publisher: activity.publisher,
        images: activity.images || []
      },
      editErrors: {
        title: '', subtitle: '', description: '', startDate: '', startTime: '', endDate: '', endTime: '', 
        registrationDeadlineDate: '', registrationDeadlineTime: '', maxParticipants: '', contact: '', 
        phone: '', location: '', publisher: '', images: ''
      }
    })
  },

  // 隐藏编辑活动弹窗
  onHideEditModal() {
    this.setData({ showEditModal: false })
  },

  // 编辑表单输入
  onEditFormInput(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    this.setData({
      [`editFormData.${field}`]: value
    })
    
    // 实时校验并清除错误提示
    this.clearEditFieldError(field, value)
  },

  // 编辑开关切换
  onEditSwitchChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    this.setData({
      [`editFormData.${field}`]: value
    })
    
    // 如果关闭了报名开关，清除报名截止时间相关数据
    if (field === 'registrationRequired' && !value) {
      this.setData({
        'editFormData.registrationDeadlineDate': '',
        'editFormData.registrationDeadlineTime': '',
        'editErrors.registrationDeadlineDate': '',
        'editErrors.registrationDeadlineTime': ''
      })
    }
    
    console.log('编辑开关切换:', { field, value })
  },

  // 编辑日期选择器变化
  onEditDateChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    console.log('编辑日期选择器变化:', { field, value })
    
    // 更新表单数据
    this.setData({
      [`editFormData.${field}`]: value
    })
    
    // 清除对应字段的错误状态
    if (value && this.data.editErrors[field]) {
      this.setData({ [`editErrors.${field}`]: '' })
    }
    
    // 验证时间逻辑
    this.validateEditDateTimeLogic()
  },

  // 编辑时间选择器变化
  onEditTimeChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    console.log('编辑时间选择器变化:', { field, value })
    
    // 更新表单数据
    this.setData({
      [`editFormData.${field}`]: value
    })
    
    // 清除对应字段的错误状态
    if (value && this.data.editErrors[field]) {
      this.setData({ [`editErrors.${field}`]: '' })
    }
    
    // 验证时间逻辑
    this.validateEditDateTimeLogic()
  },

  // 校验编辑日期时间逻辑
  validateEditDateTimeLogic() {
    const { startDate, startTime, endDate, endTime, registrationDeadlineDate, registrationDeadlineTime } = this.data.editFormData
    
    // 如果开始日期和结束日期都选择了
    if (startDate && endDate) {
      const startDateTime = new Date(`${startDate} ${startTime || '00:00'}`)
      const endDateTime = new Date(`${endDate} ${endTime || '00:00'}`)
      
      if (endDateTime <= startDateTime) {
        this.setData({ 'editErrors.endDate': '结束时间必须晚于开始时间' })
      } else {
        // 清除结束时间错误
        if (this.data.editErrors.endDate) {
          this.setData({ 'editErrors.endDate': '' })
        }
      }
    }
    
    // 校验报名截止时间必须早于活动开始时间（只在需要报名时校验）
    if (this.data.editFormData.registrationRequired && registrationDeadlineDate && registrationDeadlineTime && startDate && startTime) {
      const registrationDeadlineDateTime = new Date(`${registrationDeadlineDate} ${registrationDeadlineTime}`)
      const startDateTime = new Date(`${startDate} ${startTime}`)
      
      if (registrationDeadlineDateTime >= startDateTime) {
        this.setData({ 'editErrors.registrationDeadlineDate': '报名截止时间必须早于活动开始时间' })
      } else {
        // 清除报名截止时间错误
        if (this.data.editErrors.registrationDeadlineDate) {
          this.setData({ 'editErrors.registrationDeadlineDate': '' })
        }
      }
    }
  },

  // 清除编辑字段错误提示
  clearEditFieldError(field, value) {
    if (!value || !value.trim()) {
      return
    }

    let isValid = true
    let errorMessage = ''

    switch (field) {
      case 'title':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '活动标题至少需要2个字符'
        } else if (value.trim().length > 50) {
          isValid = false
          errorMessage = '活动标题不能超过50个字符'
        }
        break
      case 'subtitle':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '活动副标题至少需要2个字符'
        } else if (value.trim().length > 30) {
          isValid = false
          errorMessage = '活动副标题不能超过30个字符'
        }
        break
      case 'description':
        if (value.trim().length < 10) {
          isValid = false
          errorMessage = '活动描述至少需要10个字符'
        } else if (value.trim().length > 500) {
          isValid = false
          errorMessage = '活动描述不能超过500个字符'
        }
        break
      case 'maxParticipants':
        const maxParticipants = parseInt(value)
        if (isNaN(maxParticipants) || maxParticipants <= 0) {
          isValid = false
          errorMessage = '参与人数必须是大于0的整数'
        } else if (maxParticipants > 10000) {
          isValid = false
          errorMessage = '参与人数不能超过10000人'
        }
        break
      case 'contact':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '负责人姓名至少需要2个字符'
        } else if (value.trim().length > 20) {
          isValid = false
          errorMessage = '负责人姓名不能超过20个字符'
        } else if (!/^[\u4e00-\u9fa5a-zA-Z\s]+$/.test(value.trim())) {
          isValid = false
          errorMessage = '负责人姓名只能包含中文、英文和空格'
        }
        break
      case 'phone':
        const phoneRegex = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$|^400-?\d{3}-?\d{4}$/
        if (!phoneRegex.test(value.trim())) {
          isValid = false
          errorMessage = '请输入正确的手机号码或固定电话'
        }
        break
      case 'location':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '活动地点至少需要2个字符'
        } else if (value.trim().length > 100) {
          isValid = false
          errorMessage = '活动地点不能超过100个字符'
        }
        break
      case 'publisher':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '活动发布方至少需要2个字符'
        } else if (value.trim().length > 50) {
          isValid = false
          errorMessage = '活动发布方不能超过50个字符'
        }
        break
    }

    // 如果字段有效，清除错误提示
    if (isValid && this.data.editErrors[field]) {
      this.setData({ [`editErrors.${field}`]: '' })
    }
  },

  // 选择编辑图片
  onChooseEditImage() {
    const { images } = this.data.editFormData
    const remainingCount = 5 - images.length
    
    if (remainingCount <= 0) {
      wx.showToast({ title: '最多只能上传5张图片', icon: 'none' })
      return
    }
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        const newImages = [...images, ...tempFilePaths]
        
        this.setData({
          'editFormData.images': newImages
        })
        
        // 清除图片相关错误
        if (this.data.editErrors.images) {
          this.setData({ 'editErrors.images': '' })
        }
    
    wx.showToast({
          title: `已添加${tempFilePaths.length}张图片`,
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        wx.showToast({ title: '选择图片失败', icon: 'none' })
      }
    })
  },

  // 删除编辑图片
  onDeleteEditImage(e) {
    const { index } = e.currentTarget.dataset
    const { images } = this.data.editFormData
    const newImages = images.filter((_, i) => i !== index)
    
    this.setData({
      'editFormData.images': newImages
    })
    
    wx.showToast({
      title: '已删除图片',
      icon: 'success'
    })
  },

  // 表单输入
  onFormInput(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value
    })
    
    // 实时校验并清除错误提示
    this.clearFieldError(field, value)
  },

  // 开关切换
  onSwitchChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value
    })
    
    // 如果关闭了报名开关，清除报名截止时间相关数据
    if (field === 'registrationRequired' && !value) {
      this.setData({
        'formData.registrationDeadlineDate': '',
        'formData.registrationDeadlineTime': '',
        'errors.registrationDeadlineDate': '',
        'errors.registrationDeadlineTime': ''
      })
    }
    
    console.log('开关切换:', { field, value })
  },

  // 清除字段错误提示
  clearFieldError(field, value) {
    if (!value || !value.trim()) {
      return
    }

    let isValid = true
    let errorMessage = ''

    switch (field) {
      case 'title':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '活动标题至少需要2个字符'
        } else if (value.trim().length > 50) {
          isValid = false
          errorMessage = '活动标题不能超过50个字符'
        }
        break
      case 'subtitle':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '活动副标题至少需要2个字符'
        } else if (value.trim().length > 30) {
          isValid = false
          errorMessage = '活动副标题不能超过30个字符'
        }
        break
      case 'description':
        if (value.trim().length < 10) {
          isValid = false
          errorMessage = '活动描述至少需要10个字符'
        } else if (value.trim().length > 500) {
          isValid = false
          errorMessage = '活动描述不能超过500个字符'
        }
        break
      case 'maxParticipants':
        const maxParticipants = parseInt(value)
        if (isNaN(maxParticipants) || maxParticipants <= 0) {
          isValid = false
          errorMessage = '参与人数必须是大于0的整数'
        } else if (maxParticipants > 10000) {
          isValid = false
          errorMessage = '参与人数不能超过10000人'
        }
        break
      case 'contact':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '负责人姓名至少需要2个字符'
        } else if (value.trim().length > 20) {
          isValid = false
          errorMessage = '负责人姓名不能超过20个字符'
        } else if (!/^[\u4e00-\u9fa5a-zA-Z\s]+$/.test(value.trim())) {
          isValid = false
          errorMessage = '负责人姓名只能包含中文、英文和空格'
        }
        break
      case 'phone':
        const phoneRegex = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$|^400-?\d{3}-?\d{4}$/
        if (!phoneRegex.test(value.trim())) {
          isValid = false
          errorMessage = '请输入正确的手机号码或固定电话'
        }
        break
      case 'location':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '活动地点至少需要2个字符'
        } else if (value.trim().length > 100) {
          isValid = false
          errorMessage = '活动地点不能超过100个字符'
        }
        break
      case 'publisher':
        if (value.trim().length < 2) {
          isValid = false
          errorMessage = '活动发布方至少需要2个字符'
        } else if (value.trim().length > 50) {
          isValid = false
          errorMessage = '活动发布方不能超过50个字符'
        }
        break
    }

    // 如果字段有效，清除错误提示
    if (isValid && this.data.errors[field]) {
      this.setData({ [`errors.${field}`]: '' })
    }
  },

  // 选择图片
  onChooseImage() {
    const { images } = this.data.formData
    const remainingCount = 5 - images.length
    
    if (remainingCount <= 0) {
      wx.showToast({ title: '最多只能上传5张图片', icon: 'none' })
      return
    }
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        const newImages = [...images, ...tempFilePaths]
        
        this.setData({
          'formData.images': newImages
        })
        
        // 清除图片相关错误
        if (this.data.errors.images) {
          this.setData({ 'errors.images': '' })
        }
        
        wx.showToast({
          title: `已添加${tempFilePaths.length}张图片`,
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        wx.showToast({ title: '选择图片失败', icon: 'none' })
      }
    })
  },

  // 日期选择器变化
  onDateChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    console.log('日期选择器变化:', { field, value })
    
    // 更新表单数据
    this.setData({
      [`formData.${field}`]: value
    })
    
    // 清除对应字段的错误状态
    if (value && this.data.errors[field]) {
      this.setData({ [`errors.${field}`]: '' })
    }
    
    // 验证时间逻辑
    this.validateDateTimeLogic()
  },

  // 时间选择器变化
  onTimeChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    console.log('时间选择器变化:', { field, value })
    
    // 更新表单数据
    this.setData({
      [`formData.${field}`]: value
    })
    
    // 清除对应字段的错误状态
    if (value && this.data.errors[field]) {
      this.setData({ [`errors.${field}`]: '' })
    }
    
    // 验证时间逻辑
    this.validateDateTimeLogic()
  },

  // 时间选择器取消
  onTimeCancel(e) {
    console.log('时间选择器取消')
  },

  // 校验日期时间逻辑
  validateDateTimeLogic() {
    const { startDate, startTime, endDate, endTime, registrationDeadlineDate, registrationDeadlineTime } = this.data.formData
    
    // 如果开始日期和结束日期都选择了
    if (startDate && endDate) {
      const startDateTime = new Date(`${startDate} ${startTime || '00:00'}`)
      const endDateTime = new Date(`${endDate} ${endTime || '00:00'}`)
      
      if (endDateTime <= startDateTime) {
        this.setData({ 'errors.endDate': '结束时间必须晚于开始时间' })
      } else {
        // 清除结束时间错误
        if (this.data.errors.endDate) {
          this.setData({ 'errors.endDate': '' })
        }
      }
    }
    
    // 校验报名截止时间必须早于活动开始时间（只在需要报名时校验）
    if (this.data.formData.registrationRequired && registrationDeadlineDate && registrationDeadlineTime && startDate && startTime) {
      const registrationDeadlineDateTime = new Date(`${registrationDeadlineDate} ${registrationDeadlineTime}`)
      const startDateTime = new Date(`${startDate} ${startTime}`)
      
      if (registrationDeadlineDateTime >= startDateTime) {
        this.setData({ 'errors.registrationDeadlineDate': '报名截止时间必须早于活动开始时间' })
      } else {
        // 清除报名截止时间错误
        if (this.data.errors.registrationDeadlineDate) {
          this.setData({ 'errors.registrationDeadlineDate': '' })
        }
      }
    }
  },

  // 校验时间逻辑（保留原有函数以兼容）
  validateTimeLogic(startTime, endTime) {
    if (startTime && endTime) {
      const startDate = new Date(startTime)
      const endDate = new Date(endTime)
      if (endDate <= startDate) {
        this.setData({ 'errors.endTime': '结束时间必须晚于开始时间' })
      } else {
        // 清除结束时间错误
        if (this.data.errors.endTime) {
          this.setData({ 'errors.endTime': '' })
        }
      }
    }
  },

  // 删除图片
  onDeleteImage(e) {
    const { index } = e.currentTarget.dataset
    const { images } = this.data.formData
    const newImages = images.filter((_, i) => i !== index)
    
    this.setData({
      'formData.images': newImages
    })
    
    wx.showToast({
      title: '已删除图片',
      icon: 'success'
    })
  },


  // 提交创建活动
  async onSubmitCreate() {
    const { formData } = this.data
    const errors = this.validateForm(formData)
    if (this.hasErrors(errors)) {
      this.setData({ errors })
      return
    }

    // 获取当前用户信息
    const currentUser = getCurrentUser()
    if (!currentUser) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    try {
      // 先上传图片
      const uploadedImages = await this.uploadImages(formData.images)
      
      // 准备API请求数据
      const apiData = {
        title: formData.title.trim(),
        subtitle: formData.subtitle.trim(),
        content: formData.description.trim(),
        startDate: formData.startDate,
        startTime: formData.startTime,
        endDate: formData.endDate,
        endTime: formData.endTime,
        maxParticipants: parseInt(formData.maxParticipants),
        contactPerson: formData.contact.trim(),
        contactPhone: formData.phone.trim(),
        location: formData.location.trim(),
        organizer: formData.publisher.trim(),
        registrationRequired: Boolean(formData.registrationRequired), // 确保是布尔值
        registrationDeadline: formData.registrationDeadlineDate && formData.registrationDeadlineTime ? 
          `${formData.registrationDeadlineDate}T${formData.registrationDeadlineTime}:00` : null,
        createdBy: currentUser.userId, // 添加创建人ID
        backgroundColor: this.generateRandomBackgroundColor(), // 添加随机背景色
        images: uploadedImages
      }

      console.log('创建活动 - 发送数据:', {
        apiData: apiData,
        registrationRequiredType: typeof apiData.registrationRequired,
        registrationRequiredValue: apiData.registrationRequired
      })

      // 调用API创建活动
      const result = await createActivity(apiData)
      
      if (result.success) {
                // 数据加载完成，隐藏全局加载
        this.hideGlobalLoading();
        // 重新加载活动列表
        await this.loadActivities()
        
        this.setData({
          showCreateModal: false
        })
        
        wx.showToast({
          title: '创建成功！',
          icon: 'success'
        })
      } else {
        throw new Error(result.message || '创建失败')
      }
    } catch (error) {
      console.error('创建活动失败:', error)
      wx.showToast({
        title: error.message || '创建失败，请重试',
        icon: 'none'
      })
    }
  },

  // 上传图片到服务器
  async uploadImages(images) {
    if (!images || images.length === 0) {
      return []
    }

    const uploadPromises = images.map((imagePath, index) => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'http://localhost:3000/api/upload/multiple',
          filePath: imagePath,
          name: 'images',
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (data.success) {
                // 构建完整的图片URL
                const imageUrl = `http://localhost:3000${data.data.files[0].url}`
                resolve({
                  url: imageUrl,
                  name: `image_${index + 1}`,
                  sortOrder: index,
                  isCover: index === 0
                })
              } else {
                reject(new Error(data.message || '图片上传失败'))
              }
            } catch (error) {
              reject(new Error('解析上传响应失败'))
            }
          },
          fail: (error) => {
            reject(new Error('图片上传失败'))
          }
        })
      })
    })

    try {
      const uploadedImages = await Promise.all(uploadPromises)
      return uploadedImages
    } catch (error) {
      throw new Error('图片上传失败: ' + error.message)
    }
  },

  // 格式化图片数据为API需要的格式（保留原方法以兼容）
  formatImagesForAPI(images) {
    if (!images || images.length === 0) {
      return []
    }
    
    // 获取活动标题，用于图片命名
    const activityTitle = this.data.formData.title || '活动'
    
    return images.map((imageUrl, index) => {
      // 从图片URL中提取文件扩展名
      const getFileExtension = (url) => {
        const match = url.match(/\.([a-zA-Z0-9]+)(?:\?|$)/)
        return match ? `.${match[1]}` : '.jpg' // 默认为.jpg格式
      }
      
      const fileExtension = getFileExtension(imageUrl)
      
      return {
        url: imageUrl,
        name: `${activityTitle}_${index + 1}${fileExtension}`,
        sortOrder: index,
        isCover: index === 0 // 第一张图片设为封面
      }
    })
  },


  // 格式化时间为显示格式
  formatTimeForDisplay(dateString) {
    if (!dateString) return ''
    
    console.log('格式化显示时间:', dateString)
    
    // 如果已经是显示格式，直接返回
    if (dateString.includes(' ') && !dateString.includes('T')) {
      return dateString
    }
    
    // 处理ISO格式，转换为显示格式
    if (dateString.includes('T')) {
      const date = new Date(dateString)
      if (isNaN(date.getTime())) {
        return dateString
      }
      
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      
      return `${year}-${month}-${day} ${hour}:${minute}`
    }
    
    // 处理datetime模式返回的格式 "YYYY-MM-DD HH:mm"
    return dateString
  },

  // 格式化日期为picker组件需要的格式 (YYYY-MM-DD)
  formatDateForPicker(dateString) {
    if (!dateString) return ''
    
    console.log('格式化日期为picker格式:', dateString)
    
    let datePart = ''
    
    // 如果已经是YYYY-MM-DD格式，直接使用
    if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) {
      datePart = dateString
      console.log('已经是正确格式:', datePart)
    }
    // 处理ISO格式 (2024-01-01T10:00:00.000Z 或 2024-01-01T10:00:00)
    else if (dateString.includes('T')) {
      datePart = dateString.split('T')[0]
      console.log('ISO格式提取日期:', datePart)
    }
    // 处理空格分隔格式 (2024-01-01 10:00:00)
    else if (dateString.includes(' ')) {
      datePart = dateString.split(' ')[0]
      console.log('空格格式提取日期:', datePart)
    }
    else {
      console.log('无法解析的日期格式，返回空字符串')
      return ''
    }
    
    // 直接返回日期部分，不进行任何+1/-1操作
    console.log('格式化结果:', datePart)
    return datePart
  },

  // 格式化时间为picker组件需要的格式 (HH:mm)
  formatTimeForPicker(timeString) {
    if (!timeString) return ''
    
    console.log('格式化时间为picker格式:', timeString)
    
    // 如果已经是HH:mm格式，直接返回
    if (timeString.match(/^\d{2}:\d{2}$/)) {
      console.log('已经是正确格式:', timeString)
      return timeString
    }
    
    // 如果只是时间格式 (HH:mm:ss)，提取HH:mm部分
    if (timeString.match(/^\d{2}:\d{2}:\d{2}$/)) {
      const result = timeString.split(':').slice(0, 2).join(':')
      console.log('纯时间格式解析结果:', result)
      return result
    }
    
    // 处理ISO格式 (2024-01-01T10:00:00.000Z 或 2024-01-01T10:00:00)
    if (timeString.includes('T')) {
      const timePart = timeString.split('T')[1]
      if (timePart) {
        // 提取HH:mm部分，去掉秒和毫秒
        const result = timePart.split(':').slice(0, 2).join(':')
        console.log('ISO格式时间解析结果:', result)
        return result
      }
    }
    
    // 处理空格分隔格式 (2024-01-01 10:00:00)
    if (timeString.includes(' ')) {
      const timePart = timeString.split(' ')[1]
      if (timePart) {
        // 提取HH:mm部分，去掉秒
        const result = timePart.split(':').slice(0, 2).join(':')
        console.log('空格格式时间解析结果:', result)
        return result
      }
    }
    
    console.log('无法解析的时间格式，返回空字符串')
    return ''
  },

  // 格式化日期为API需要的格式，对日期进行-1操作补偿时区差异
  formatDateForAPI(dateString) {
    if (!dateString) return null
    
    console.log('格式化日期为API格式:', dateString)
    
    // 直接转换为ISO格式，不进行任何+1/-1操作
    const date = new Date(dateString)
    const result = date.toISOString()
    console.log('API格式结果:', dateString, '->', result)
    return result
  },

  // 格式化时间为API需要的格式
  formatTimeForAPI(dateString) {
    if (!dateString) return ''
    
    // 如果已经是ISO格式，直接返回
    if (dateString.includes('T')) {
      return dateString
    }
    
    // 处理datetime模式返回的格式 "YYYY-MM-DD HH:mm"
    if (dateString.includes(' ')) {
      // 将空格替换为T，形成ISO格式
      return dateString.replace(' ', 'T') + ':00'
    }
    
    // 处理纯日期格式，添加默认时间
    const date = new Date(dateString)
    if (isNaN(date.getTime())) {
      return dateString
    }
    
    return date.toISOString()
  },

  // 格式化时间显示
  formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
  },

  // 查看活动详情
  onViewActivityDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/activity/detail/index?id=${id}`,
      success: () => console.log('跳转到活动详情页面成功'),
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    })
  },

  // 删除活动
  onDeleteActivity(e) {
    const { activity } = e.currentTarget.dataset
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${activity.title}"活动吗？此操作不可恢复。`,
      confirmText: '删除',
      cancelText: '取消',
      confirmColor: '#ef4444',
      success: (res) => {
        if (res.confirm) {
          this.deleteActivity(activity.id)
        }
      }
    })
  },

  // 执行删除活动
  async deleteActivity(id) {
    try {
      // 调用API删除活动
      const result = await deleteActivity(id)
      
      if (result.success) {
        // 重新加载活动列表
        await this.loadActivities()
        
        wx.showToast({
          title: '删除成功！',
          icon: 'success'
        })
      } else {
        throw new Error(result.message || '删除失败')
      }
    } catch (error) {
      console.error('删除活动失败:', error)
      wx.showToast({
        title: error.message || '删除失败，请重试',
        icon: 'none'
      })
    }
  },

  // 更新活动状态
  onUpdateActivityStatus(e) {
    const { activity, status } = e.currentTarget.dataset
    
    let statusText = ''
    switch(status) {
      case 'active':
        statusText = '进行中'
        break
      case 'completed':
        statusText = '已结束'
        break
      case 'upcoming':
        statusText = '即将开始'
        break
    }
    
    wx.showModal({
      title: '确认更新',
      content: `确定要将"${activity.title}"活动状态更新为"${statusText}"吗？`,
      confirmText: '确认',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.updateActivityStatus(activity.id, status, statusText)
        }
      }
    })
  },

  // 执行更新活动状态
  async updateActivityStatus(id, status, statusText) {
    try {
      // 调用API更新活动状态
      const result = await updateActivityStatus(id, status)
      
      if (result.success) {
        // 重新加载活动列表
        await this.loadActivities()
        
        wx.showToast({
          title: '状态更新成功！',
          icon: 'success'
        })
      } else {
        throw new Error(result.message || '状态更新失败')
      }
    } catch (error) {
      console.error('更新活动状态失败:', error)
      wx.showToast({
        title: error.message || '状态更新失败，请重试',
        icon: 'none'
      })
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadActivities()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  }
  ,
  // 校验表单
  validateForm(formData) {
    const errors = {
      title: '',
      subtitle: '',
      description: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
      registrationDeadlineDate: '',
      registrationDeadlineTime: '',
      maxParticipants: '',
      contact: '',
      phone: '',
      location: '',
      publisher: '',
      images: ''
    }

    // 校验活动标题
    if (!formData.title || !formData.title.trim()) {
      errors.title = '请填写活动标题'
    } else if (formData.title.trim().length < 2) {
      errors.title = '活动标题至少需要2个字符'
    } else if (formData.title.trim().length > 50) {
      errors.title = '活动标题不能超过50个字符'
    }

    // 校验活动副标题
    if (!formData.subtitle || !formData.subtitle.trim()) {
      errors.subtitle = '请填写活动副标题'
    } else if (formData.subtitle.trim().length < 2) {
      errors.subtitle = '活动副标题至少需要2个字符'
    } else if (formData.subtitle.trim().length > 30) {
      errors.subtitle = '活动副标题不能超过30个字符'
    }

    // 校验活动描述
    if (!formData.description || !formData.description.trim()) {
      errors.description = '请填写活动描述'
    } else if (formData.description.trim().length < 10) {
      errors.description = '活动描述至少需要10个字符'
    } else if (formData.description.trim().length > 500) {
      errors.description = '活动描述不能超过500个字符'
    }

    // 校验开始日期
    if (!formData.startDate) {
      errors.startDate = '请选择开始日期'
    } else {
      const startDate = new Date(formData.startDate)
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      if (startDate < today) {
        errors.startDate = '开始日期不能早于今天'
      }
    }

    // 校验开始时间
    if (!formData.startTime) {
      errors.startTime = '请选择开始时间'
    }

    // 校验结束日期
    if (!formData.endDate) {
      errors.endDate = '请选择结束日期'
    }

    // 校验结束时间
    if (!formData.endTime) {
      errors.endTime = '请选择结束时间'
    }

    // 校验时间逻辑
    if (formData.startDate && formData.endDate) {
      const startDateTime = new Date(`${formData.startDate} ${formData.startTime || '00:00'}`)
      const endDateTime = new Date(`${formData.endDate} ${formData.endTime || '00:00'}`)
      
      if (endDateTime <= startDateTime) {
        errors.endDate = '结束时间必须晚于开始时间'
      }
    }

    // 校验报名截止时间（只在需要报名时校验）
    if (formData.registrationRequired && formData.registrationDeadlineDate && formData.registrationDeadlineTime) {
      const registrationDeadlineDateTime = new Date(`${formData.registrationDeadlineDate} ${formData.registrationDeadlineTime}`)
      const startDateTime = new Date(`${formData.startDate} ${formData.startTime || '00:00'}`)
      
      if (registrationDeadlineDateTime >= startDateTime) {
        errors.registrationDeadlineDate = '报名截止时间必须早于活动开始时间'
      }
    }

    // 校验最大参与人数
    if (!formData.maxParticipants || !`${formData.maxParticipants}`.trim()) {
      errors.maxParticipants = '请填写最大参与人数'
    } else {
      const maxParticipants = parseInt(formData.maxParticipants)
      if (isNaN(maxParticipants) || maxParticipants <= 0) {
        errors.maxParticipants = '参与人数必须是大于0的整数'
      } else if (maxParticipants > 10000) {
        errors.maxParticipants = '参与人数不能超过10000人'
      }
    }

    // 校验负责人姓名
    if (!formData.contact || !formData.contact.trim()) {
      errors.contact = '请填写负责人姓名'
    } else if (formData.contact.trim().length < 2) {
      errors.contact = '负责人姓名至少需要2个字符'
    } else if (formData.contact.trim().length > 20) {
      errors.contact = '负责人姓名不能超过20个字符'
    } else if (!/^[\u4e00-\u9fa5a-zA-Z\s]+$/.test(formData.contact.trim())) {
      errors.contact = '负责人姓名只能包含中文、英文和空格'
    }

    // 校验联系电话
    if (!formData.phone || !formData.phone.trim()) {
      errors.phone = '请填写联系电话'
    } else {
      const phone = formData.phone.trim()
      const phoneRegex = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$|^400-?\d{3}-?\d{4}$/
      if (!phoneRegex.test(phone)) {
        errors.phone = '请输入正确的手机号码或固定电话'
      }
    }

    // 校验活动地点
    if (!formData.location || !formData.location.trim()) {
      errors.location = '请填写活动地点'
    } else if (formData.location.trim().length < 2) {
      errors.location = '活动地点至少需要2个字符'
    } else if (formData.location.trim().length > 100) {
      errors.location = '活动地点不能超过100个字符'
    }

    // 校验活动发布方
    if (!formData.publisher || !formData.publisher.trim()) {
      errors.publisher = '请填写活动发布方'
    } else if (formData.publisher.trim().length < 2) {
      errors.publisher = '活动发布方至少需要2个字符'
    } else if (formData.publisher.trim().length > 50) {
      errors.publisher = '活动发布方不能超过50个字符'
    }

    // 校验活动图片
    if (!formData.images || formData.images.length === 0) {
      errors.images = '请至少上传1张活动图片'
    } else if (formData.images.length > 5) {
      errors.images = '最多只能上传5张图片'
    }

    return errors
  },

  // 校验编辑表单
  validateEditForm(formData) {
    const errors = {
      title: '',
      subtitle: '',
      description: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
      registrationDeadlineDate: '',
      registrationDeadlineTime: '',
      maxParticipants: '',
      contact: '',
      phone: '',
      location: '',
      publisher: '',
      images: ''
    }

    // 校验活动标题
    if (!formData.title || !formData.title.trim()) {
      errors.title = '请填写活动标题'
    } else if (formData.title.trim().length < 2) {
      errors.title = '活动标题至少需要2个字符'
    } else if (formData.title.trim().length > 50) {
      errors.title = '活动标题不能超过50个字符'
    }

    // 校验活动副标题
    if (!formData.subtitle || !formData.subtitle.trim()) {
      errors.subtitle = '请填写活动副标题'
    } else if (formData.subtitle.trim().length < 2) {
      errors.subtitle = '活动副标题至少需要2个字符'
    } else if (formData.subtitle.trim().length > 30) {
      errors.subtitle = '活动副标题不能超过30个字符'
    }

    // 校验活动描述
    if (!formData.description || !formData.description.trim()) {
      errors.description = '请填写活动描述'
    } else if (formData.description.trim().length < 10) {
      errors.description = '活动描述至少需要10个字符'
    } else if (formData.description.trim().length > 500) {
      errors.description = '活动描述不能超过500个字符'
    }

    // 校验开始日期
    if (!formData.startDate) {
      errors.startDate = '请选择开始日期'
    } else {
      const startDate = new Date(formData.startDate)
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      if (startDate < today) {
        errors.startDate = '开始日期不能早于今天'
      }
    }

    // 校验开始时间
    if (!formData.startTime) {
      errors.startTime = '请选择开始时间'
    }

    // 校验结束日期
    if (!formData.endDate) {
      errors.endDate = '请选择结束日期'
    }

    // 校验结束时间
    if (!formData.endTime) {
      errors.endTime = '请选择结束时间'
    }

    // 校验时间逻辑
    if (formData.startDate && formData.endDate) {
      const startDateTime = new Date(`${formData.startDate} ${formData.startTime || '00:00'}`)
      const endDateTime = new Date(`${formData.endDate} ${formData.endTime || '00:00'}`)
      
      if (endDateTime <= startDateTime) {
        errors.endDate = '结束时间必须晚于开始时间'
      }
    }

    // 校验报名截止时间（只在需要报名时校验）
    if (formData.registrationRequired && formData.registrationDeadlineDate && formData.registrationDeadlineTime) {
      const registrationDeadlineDateTime = new Date(`${formData.registrationDeadlineDate} ${formData.registrationDeadlineTime}`)
      const startDateTime = new Date(`${formData.startDate} ${formData.startTime || '00:00'}`)
      
      if (registrationDeadlineDateTime >= startDateTime) {
        errors.registrationDeadlineDate = '报名截止时间必须早于活动开始时间'
      }
    }

    // 校验最大参与人数
    if (!formData.maxParticipants || !`${formData.maxParticipants}`.trim()) {
      errors.maxParticipants = '请填写最大参与人数'
    } else {
      const maxParticipants = parseInt(formData.maxParticipants)
      if (isNaN(maxParticipants) || maxParticipants <= 0) {
        errors.maxParticipants = '参与人数必须是大于0的整数'
      } else if (maxParticipants > 10000) {
        errors.maxParticipants = '参与人数不能超过10000人'
      }
    }

    // 校验负责人姓名
    if (!formData.contact || !formData.contact.trim()) {
      errors.contact = '请填写负责人姓名'
    } else if (formData.contact.trim().length < 2) {
      errors.contact = '负责人姓名至少需要2个字符'
    } else if (formData.contact.trim().length > 20) {
      errors.contact = '负责人姓名不能超过20个字符'
    } else if (!/^[\u4e00-\u9fa5a-zA-Z\s]+$/.test(formData.contact.trim())) {
      errors.contact = '负责人姓名只能包含中文、英文和空格'
    }

    // 校验联系电话
    if (!formData.phone || !formData.phone.trim()) {
      errors.phone = '请填写联系电话'
    } else {
      const phone = formData.phone.trim()
      const phoneRegex = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$|^400-?\d{3}-?\d{4}$/
      if (!phoneRegex.test(phone)) {
        errors.phone = '请输入正确的手机号码或固定电话'
      }
    }

    // 校验活动地点
    if (!formData.location || !formData.location.trim()) {
      errors.location = '请填写活动地点'
    } else if (formData.location.trim().length < 2) {
      errors.location = '活动地点至少需要2个字符'
    } else if (formData.location.trim().length > 100) {
      errors.location = '活动地点不能超过100个字符'
    }

    // 校验活动发布方
    if (!formData.publisher || !formData.publisher.trim()) {
      errors.publisher = '请填写活动发布方'
    } else if (formData.publisher.trim().length < 2) {
      errors.publisher = '活动发布方至少需要2个字符'
    } else if (formData.publisher.trim().length > 50) {
      errors.publisher = '活动发布方不能超过50个字符'
    }

    // 校验活动图片
    if (!formData.images || formData.images.length === 0) {
      errors.images = '请至少上传1张活动图片'
    } else if (formData.images.length > 5) {
      errors.images = '最多只能上传5张图片'
    }

    return errors
  },

  // 提交编辑活动
  async onSubmitEdit() {
    const { editFormData } = this.data
    const errors = this.validateEditForm(editFormData)
    if (this.hasErrors(errors)) {
      this.setData({ editErrors: errors })
      return
    }

    // 获取当前用户信息
    const currentUser = getCurrentUser()
    if (!currentUser) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    try {
      // 先上传图片
      const uploadedImages = await this.uploadEditImages(editFormData.images)
      
      // 准备API请求数据
      const apiData = {
        title: editFormData.title.trim(),
        subtitle: editFormData.subtitle.trim(),
        content: editFormData.description.trim(),
        startDate: editFormData.startDate,
        startTime: editFormData.startTime,
        endDate: editFormData.endDate,
        endTime: editFormData.endTime,
        maxParticipants: parseInt(editFormData.maxParticipants),
        contactPerson: editFormData.contact.trim(),
        contactPhone: editFormData.phone.trim(),
        location: editFormData.location.trim(),
        organizer: editFormData.publisher.trim(),
        registrationRequired: Boolean(editFormData.registrationRequired),
        registrationDeadline: editFormData.registrationDeadlineDate && editFormData.registrationDeadlineTime ? 
          `${editFormData.registrationDeadlineDate}T${editFormData.registrationDeadlineTime}:00` : null,
        images: uploadedImages
      }

      console.log('编辑活动 - 发送数据:', apiData)

      // 调用API更新活动
      const result = await updateActivity(editFormData.id, apiData)
      
      if (result.success) {
        // 重新加载活动列表
        await this.loadActivities()
        
        this.setData({
          showEditModal: false
        })
        
        wx.showToast({
          title: '保存成功！',
          icon: 'success'
        })
      } else {
        throw new Error(result.message || '保存失败')
      }
    } catch (error) {
            this.hideGlobalLoading();
      console.error('编辑活动失败:', error)
      wx.showToast({
        title: error.message || '保存失败，请重试',
        icon: 'none'
      })
    }
  },

  // 上传编辑图片到服务器
  async uploadEditImages(images) {
    if (!images || images.length === 0) {
      return []
    }

    // 分离新上传的图片和已有的图片URL
    const newImages = []
    const existingImages = []
    
    images.forEach(image => {
      if (typeof image === 'string' && image.startsWith('http')) {
        // 这是已有的图片URL
        existingImages.push({
          url: image,
          name: `existing_image_${existingImages.length + 1}`,
          sortOrder: existingImages.length,
          isCover: existingImages.length === 0
        })
      } else {
        // 这是新上传的图片路径
        newImages.push(image)
      }
    })

    // 上传新图片
    if (newImages.length > 0) {
      const uploadPromises = newImages.map((imagePath, index) => {
        return new Promise((resolve, reject) => {
          wx.uploadFile({
            url: 'http://localhost:3000/api/upload/multiple',
            filePath: imagePath,
            name: 'images',
            success: (res) => {
              try {
                const data = JSON.parse(res.data)
                if (data.success) {
                  // 构建完整的图片URL
                  const imageUrl = `http://localhost:3000${data.data.files[0].url}`
                  resolve({
                    url: imageUrl,
                    name: `image_${index + 1}`,
                    sortOrder: existingImages.length + index,
                    isCover: existingImages.length === 0 && index === 0
                  })
                } else {
                  reject(new Error(data.message || '图片上传失败'))
                }
              } catch (error) {
                reject(new Error('解析上传响应失败'))
              }
            },
            fail: (error) => {
              reject(new Error('图片上传失败'))
            }
          })
        })
      })

      try {
        const uploadedNewImages = await Promise.all(uploadPromises)
        return [...existingImages, ...uploadedNewImages]
      } catch (error) {
        throw new Error('图片上传失败: ' + error.message)
      }
    }

    return existingImages
  },

  hasErrors(errors) {
    return Object.keys(errors).some(k => !!errors[k])
  }
})